package com.example.dynamicdatasource.config.scheduler;

import com.example.dynamicdatasource.config.datasource.LazyDynamicDataSource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

@Component
@Slf4j
@RequiredArgsConstructor
public class DataSourceCleanupScheduler {

    private final DataSource dataSource;

    @Value("${datasource.timeout-minutes:1}")
    private long timeoutMinutes;

    // 每10分钟执行一次
    @Scheduled(fixedRate = 1000 * 30 * 1)
    public void cleanupTimeoutDataSources() {
        if (dataSource instanceof LazyDynamicDataSource) {
            long timeoutMillis = timeoutMinutes * 60 * 1000;
            log.info("开始检查超时数据源，超时时间: {}分钟", timeoutMinutes);
            ((LazyDynamicDataSource) dataSource).closeTimeoutDataSources(timeoutMillis);
            log.info("超时数据源检查完成");
        }
    }
}
